<script lang="ts" setup>
import type { HookPluginType } from '../../types';

import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { useVbenModal } from '@vben/common-ui';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getHooksPlugins, postHooksPluginsOrder } from '#/api/admin/hooks';

const hookName = ref('');
const gridOptions: VxeGridProps<HookPluginType> = {
  rowConfig: {
    useKey: true,
    drag: true,
  },
  columnConfig: {
    useKey: true,
  },
  columns: [
    { title: '序号', type: 'seq', width: 50, dragSort: true },
    { field: 'title', title: '名称' },
    { field: 'plugin', title: '标识' },
    { field: 'hook', title: '钩子' },
    { field: 'author', title: '作者' },
    { field: 'description', title: '描述' },
    { field: 'status', title: '状态', slots: { default: 'status' } },
  ],
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async () => {
        const { data } = await getHooksPlugins(hookName.value);
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

const gridEvents: VxeGridListeners<any> = {
  async rowDragend() {
    const visibleData = await GridApi.grid.getTableData().visibleData;
    const result: { [key: string]: number } = {};
    // 使用 forEach 替代 reduce
    visibleData.forEach((item, index) => {
      result[item.id] = index;
    });
    await postHooksPluginsOrder({ list_orders: result });
  },
};

const [Modal, modalApi] = useVbenModal({
  onOpenChange(isOpen) {
    if (isOpen) {
      const modalData = modalApi.getData();
      hookName.value = modalData.hook;
    }
  },
});
</script>
<template>
  <Modal :footer="false" class="w-3/5">
    <Grid :grid-events="gridEvents" table-title="插件列表">
      <template #status="{ row }">
        {{ row.status ? '开启' : '禁用' }}
      </template>
    </Grid>
  </Modal>
</template>
